package com.dhcc.ws.common.interceptor;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
 
 
public class WebServiceInterceptor extends
		AbstractPhaseInterceptor<SoapMessage> {
 
	public WebServiceInterceptor() {
		super(Phase.PRE_INVOKE);
	}
 
	public void handleMessage(SoapMessage soapMsg) throws Fault {
		List<Header> headers = soapMsg.getHeaders();// 根据soap消息获取头部
		if (headers == null || headers.size() == 0) {
			throw new Fault(new IllegalArgumentException("拒绝访问，原因：没有header！"));
		}
		for (Header header : headers) {
			Element ele = (Element) header.getObject();
			NodeList nodeList = ele.getElementsByTagName("token");
			if (nodeList == null || nodeList.getLength() == 0) {
				throw new Fault(new IllegalArgumentException("拒绝访问，原因：通行信息为空！"));
			}
			String token = nodeList.item(0).getTextContent();
			if (StringUtils.isNotBlank(token)) {
				boolean tokenFlag = this.validRequestClient(token);
				if (!tokenFlag) {
					throw new Fault(new IllegalArgumentException(
							"拒绝访问，原因：通行信息验证未通过！"));
				}
			} else {
				throw new Fault(new IllegalArgumentException("拒绝访问，原因：通行信息为空！"));
			}
		}
 
	}
	private boolean validRequestClient(String token) {
		System.out.println(token);
		return true;
	}
 
}